using Senparc.Weixin.Entities;
using Senparc.Weixin.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace Senparc.Weixin.HttpUtility
{
	public static class Post
	{
		public static T GetResult<T>(string returnText)
		{
			JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
			if (returnText.Contains("errcode"))
			{
				WxJsonResult wxJsonResult = javaScriptSerializer.Deserialize<WxJsonResult>(returnText);
				if (wxJsonResult.errcode != ReturnCode.请求成功)
				{
					throw new ErrorJsonResultException(string.Format("微信Post请求发生错误！错误代码：{0}，说明：{1}", (int)wxJsonResult.errcode, wxJsonResult.errmsg), null, wxJsonResult);
				}
			}
			return javaScriptSerializer.Deserialize<T>(returnText);
		}
		public static T PostFileGetJson<T>(string url, CookieContainer cookieContainer = null, Dictionary<string, string> fileDictionary = null, Dictionary<string, string> postDataDictionary = null, Encoding encoding = null, int timeOut = 10000)
		{
			T result2;
			using (MemoryStream memoryStream = new MemoryStream())
			{
				postDataDictionary.FillFormDataStream(memoryStream);
				string returnText = RequestUtility.HttpPost(url, cookieContainer, memoryStream, fileDictionary, null, encoding, timeOut, false);
				T result = Post.GetResult<T>(returnText);
				result2 = result;
			}
			return result2;
		}
		public static T PostGetJson<T>(string url, CookieContainer cookieContainer = null, Stream fileStream = null, Encoding encoding = null, int timeOut = 10000, bool checkValidationResult = false)
		{
			string returnText = RequestUtility.HttpPost(url, cookieContainer, fileStream, null, null, encoding, timeOut, checkValidationResult);
			return Post.GetResult<T>(returnText);
		}
		public static T PostGetJson<T>(string url, CookieContainer cookieContainer = null, Dictionary<string, string> formData = null, Encoding encoding = null, int timeOut = 10000)
		{
			string returnText = RequestUtility.HttpPost(url, cookieContainer, formData, encoding, timeOut);
			return Post.GetResult<T>(returnText);
		}
		public static void Download(string url, string data, Stream stream)
		{
			WebClient webClient = new WebClient();
			byte[] array = webClient.UploadData(url, "POST", Encoding.UTF8.GetBytes(string.IsNullOrEmpty(data) ? "" : data));
			byte[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				byte value = array2[i];
				stream.WriteByte(value);
			}
		}
	}
}
